<?php

namespace Service;

use Doctrine\ORM\EntityManager;

abstract class Manager
{

    /**
     *
     * @var EntityManager
     */
    protected $_em;

    function __construct(EntityManager $em)
    {
        $this->_em = $em;
    }

    public function create(array $data)
    {
        $entityClass = "\\Entity\\" . $this->_getEntityClass();
        $entity = new $entityClass;
        $entity->appendData($data);
        $this->_em->persist($entity);
        $this->_em->flush();
        return $entity;
    }

    public function update(array $data, $id)
    {
        $entity = $this->getEntity($id);
        $entity->appendData($data);
        $this->_em->flush();
    }

    public function getEntity($id)
    {
        $entityClass = "\\Entity\\" . $this->_getEntityClass();
        return $this->_em->getRepository($entityClass)->findOneById($id);
    }

    public function getAll()
    {
        $entityClass = "\\Entity\\" . $this->_getEntityClass();
        return $this->_em->getRepository($entityClass)->findAll();
    }

    public function delete($id)
    {
        $entity = $this->getEntity($id);
        $this->_em->remove($entity);
        $this->_em->flush();
    }

    /**
     * @return \Entity\User|null
     */
    public function getUser()
    {
        if (isset($_SESSION['auth'])) {
            $userSession = unserialize($_SESSION['auth']);
            $user = $this->_em->getRepository("\Entity\User")->findOneById($userSession->getId());
            return $user;
        }
        return null;
    }

    /**
     * @return string
     */
    abstract protected function _getEntityClass();
}